// generate.js
Page({
    data: {
        formData: null,
        img: null,
        templateIndex: 0, // 默认模板索引
        activeSection: 'education', // 默认显示教育经历
        themeColor: '#007aff', // 默认主题色
        fontSize: 16, // 默认字体大小
        lineSpacing: 1.5, // 默认行间距
        sectionSpacing: 20, // 默认模块间距
        templates: [
            {
                name: '模板1',
                style: {
                    backgroundColor: '#fff',
                    color: '#333'
                },
                previewImage: '/path/to/template1_preview.png' // 模板预览图路径
            },
            {
                name: '模板2',
                style: {
                    backgroundColor: '#f0f0f0',
                    color: '#000'
                },
                previewImage: '/path/to/template2_preview.png' // 模板预览图路径
            }
            // 可以继续添加更多模板
        ],
        themeColors: ['#007aff', '#ff6347', '#32cd32', '#ff4500', '#4682b4'], // 主题色选项
        fontSizes: [14, 16, 18, 20, 22], // 字体大小选项
        lineSpacings: [1.2, 1.4, 1.6, 1.8, 2.0], // 行间距选项
        sectionSpacings: [10, 15, 20, 25, 30] // 模块间距选项
    },

    onLoad: function (options) {
        // 从本地存储中获取表单数据
        wx.getStorage({
            key: 'personalFormData',
            success: (res) => {
                this.setData({
                    formData: res.data
                });
            },
            fail: (err) => {
                console.log('获取个人表单数据失败', err);
            }
        });

        wx.getStorage({
            key: 'educationList',
            success: (res) => {
                // const educationList = res.data.map((e) => ({
                //     ...e,
                //     // startDate: e.startDate.slice(0, -3),
                //     // endDate: e.endDate.slice(0, -3)
                // }))
                // console.log(educationList)
                this.setData({
                    // [`formData.education`]: educationList
                    [`formData.education`]: res.data
                });
            },
            fail: (err) => {
                console.log('获取个人表单数据失败', err);
            }
        });

        wx.getStorage({
            key: 'experienceList',
            success: (res) => {
                // const educationList = res.data.map((e) => ({
                //     ...e,
                //     // startDate: e.startDate.slice(0, -3),
                //     // endDate: e.endDate.slice(0, -3)
                // }))
                // console.log(educationList)
                this.setData({
                    // [`formData.education`]: educationList
                    [`formData.experience`]: res.data
                });
            },
            fail: (err) => {
                console.log('获取个人表单数据失败', err);
            }
        });

        // 从本地存储中获取图片数据
        wx.getStorage({
            key: 'img',
            success: (res) => {
                this.setData({
                    img: res.data
                });
            },
            fail: (err) => {
                console.log('获取图片数据失败', err);
            }
        });

        console.log(this.data)
    },
    downloadDocument() {
        // 显示加载提示
        wx.showToast({
            title: '下载中...',
            icon: 'loading',
            duration: 2000
        });

        // 获取 resume-preview 的节点信息
        const query = wx.createSelectorQuery();
        query.select('.resume-preview').boundingClientRect();
        query.exec((res) => {
            if (res && res[0]) {
                const rect = res[0];
                const canvasWidth = rect.width;
                const canvasHeight = rect.height;

                // 设置 Canvas 的尺寸
                const canvas = wx.createCanvasContext('resumeCanvas');
                canvas.clearRect(0, 0, canvasWidth, canvasHeight);

                // 绘制 resume-preview 的内容到 Canvas
                this.drawResumePreview(canvas, rect, () => {
                    // 将 Canvas 内容转换为图片文件
                    wx.canvasToTempFilePath({
                        x: 0,
                        y: 0,
                        width: canvasWidth,
                        height: canvasHeight,
                        destWidth: canvasWidth,
                        destHeight: canvasHeight,
                        canvasId: 'resumeCanvas',
                        success: (res) => {
                            const tempFilePath = res.tempFilePath;

                            // 保存文件到用户设备
                            wx.saveImageToPhotosAlbum({
                                filePath: tempFilePath,
                                success: (saveRes) => {
                                    wx.showToast({
                                        title: '保存成功',
                                        icon: 'success',
                                        duration: 2000
                                    });
                                    console.log('文件保存路径:', saveRes.savedFilePath);

                                    // 可选：打开保存的文件
                                    wx.openDocument({
                                        filePath: saveRes.savedFilePath,
                                        fileType: 'png',
                                        success: function (openRes) {
                                            console.log('打开文档成功', openRes);
                                        },
                                        fail: function (openErr) {
                                            console.log('打开文档失败', openErr);
                                        }
                                    });
                                },
                                fail: (err) => {
                                    console.log('保存文件失败', err);
                                    wx.showToast({
                                        title: '保存失败',
                                        icon: 'none',
                                        duration: 2000
                                    });
                                }
                            });
                        },
                        fail: (err) => {
                            console.log('转换为图片失败', err);
                            wx.showToast({
                                title: '转换失败',
                                icon: 'none',
                                duration: 2000
                            });
                        }
                    });
                });
            } else {
                console.log('获取节点信息失败', res);
                wx.showToast({
                    title: '获取节点信息失败',
                    icon: 'none',
                    duration: 2000
                });
            }
        });
    },

    drawResumePreview(canvas, rect, callback) {
        // 绘制 resume-preview 的内容到 Canvas
        // 这里需要根据实际的样式和内容进行绘制
        // 以下是一个简单的示例，实际应用中需要更复杂的绘制逻辑

        const ctx = canvas;

        // 设置背景颜色
        ctx.setFillStyle(this.data.templates[this.data.templateIndex].style.backgroundColor);
        ctx.fillRect(0, 0, rect.width, rect.height);

        // 绘制侧边栏
        const sidebarWidth = rect.width * 0.25;
        ctx.setFillStyle(this.data.themeColor);
        ctx.fillRect(0, 0, sidebarWidth, rect.height);

        let sideX = 10;
        let sideY = 10;

        // 绘制头像
        if (this.data.img && this.data.img.tempFilePath) {
            ctx.drawImage(this.data.img.tempFilePath, sideX, sideY, 60, 80);
        }

        sideY += 80

        // 绘制基本信息
        const name = this.data.formData ? this.data.formData.name : '';
        const email = this.data.formData ? this.data.formData.email : '';
        const address = this.data.formData ? this.data.formData.address : '';
        const gender = this.data.formData ? this.data.formData.gender : '';

        // ctx.setFillStyle(this.data.templates[this.data.templateIndex].style.color);
        // ctx.setFontSize(this.data.fontSize);
        ctx.setFillStyle('white');
        ctx.setFontSize(8);
        sideY += 10
        if (name !== '') {
            ctx.fillText(name, sideX, sideY);
        }
        if (email !== '') {
            sideY += 10
            ctx.fillText(`邮箱：${email}`, sideX, sideY);
        }
        if (address !== '') {
            sideY += 10
            ctx.fillText(`地址：${address}`, sideX, sideY);
        }
        if (gender !== '') {
            sideY += 10
            ctx.fillText(`性别：${gender}`, sideX, sideY);
        }

        // 绘制联系方式
        const phone = this.data.formData ? this.data.formData.phone : '';

        ctx.setFillStyle(this.data.templates[this.data.templateIndex].style.color);
        ctx.setFontSize(this.data.fontSize);
        ctx.fillText('联系方式', 100, 170);
        if (phone !== '') ctx.fillText(`电话：${phone}`, 100, 200);

        // 绘制教育经历
        const education = this.data.formData ? this.data.formData.education : [];
        let y = 250;
        if (education && education.length) {
            education.forEach((item) => {
                ctx.setFillStyle(this.data.themeColor);
                ctx.setFontSize(this.data.fontSize);
                ctx.fillText('教育经历', 10, y);
                y += 30;

                ctx.setFillStyle(this.data.templates[this.data.templateIndex].style.color);
                ctx.setFontSize(this.data.fontSize - 2);
                ctx.fillText(`${item.startDate || ''} - ${item.endDate || ''}`, 10, y);
                ctx.fillText(`${item.schoolName || ''}`, 10, y + 30);
                ctx.fillText(`${item.major || ''} (${item.degree || ''})`, 10, y + 60);
                y += 90;
            });
        }

        // 绘制工作经验
        const experience = this.data.formData ? this.data.formData.experience : [];
        if (experience && experience.length) {
            experience.forEach((item) => {
                ctx.setFillStyle(this.data.themeColor);
                ctx.setFontSize(this.data.fontSize);
                ctx.fillText('工作经验', 10, y);
                y += 30;

                ctx.setFillStyle(this.data.templates[this.data.templateIndex].style.color);
                ctx.setFontSize(this.data.fontSize - 2);
                if (item.startDate && item.endDate) ctx.fillText(`${item.startDate} - ${item.endDate}`, 10, y);
                if (item.companyName) ctx.fillText(`${item.companyName}`, 10, y + 30);
                if (item.employee) ctx.fillText(`${item.employee}`, 10, y + 60);
                if (item.workContent) ctx.fillText(`${item.workContent}`, 10, y + 90);
                y += 120;
            });
        }

        // 绘制自我介绍
        const introduction = this.data.formData ? this.data.formData.introduction : '';

        if (introduction) {
            ctx.setFillStyle(this.data.themeColor);
            ctx.setFontSize(this.data.fontSize);
            ctx.fillText('自我介绍', 10, y);
            y += 30;

            ctx.setFillStyle(this.data.templates[this.data.templateIndex].style.color);
            ctx.setFontSize(this.data.fontSize - 2);
            ctx.fillText(introduction, 10, y);
            y += 60;
        }

        // 绘制完成
        ctx.draw(false, callback);
    }
    ,

    showThemeColorPicker() {
        wx.showActionSheet({
            itemList: this.data.themeColors.map(color => `颜色: ${color}`),
            success: (res) => {
                const themeColor = this.data.themeColors[res.tapIndex];
                this.setData({
                    themeColor: themeColor
                });
            },
            fail: (res) => {
                console.log(res.errMsg);
            }
        });
    },

    showFontSizePicker() {
        wx.showActionSheet({
            itemList: this.data.fontSizes.map(size => `${size}px`),
            success: (res) => {
                const fontSize = this.data.fontSizes[res.tapIndex];
                this.setData({
                    fontSize: fontSize
                });
            },
            fail: (res) => {
                console.log(res.errMsg);
            }
        });
    },

    showLineSpacingPicker() {
        wx.showActionSheet({
            itemList: this.data.lineSpacings.map(spacing => `${spacing}x`),
            success: (res) => {
                const lineSpacing = this.data.lineSpacings[res.tapIndex];
                this.setData({
                    lineSpacing: lineSpacing
                });
            },
            fail: (res) => {
                console.log(res.errMsg);
            }
        });
    },

    showSectionSpacingPicker() {
        wx.showActionSheet({
            itemList: this.data.sectionSpacings.map(spacing => `${spacing}px`),
            success: (res) => {
                const sectionSpacing = this.data.sectionSpacings[res.tapIndex];
                this.setData({
                    sectionSpacing: sectionSpacing
                });
            },
            fail: (res) => {
                console.log(res.errMsg);
            }
        });
    }
});
